// pages/2411Ayiliao-pages/recharge/outpatient.js
Page({
	data: {
		rechargeList: [],
		loading: false,
		hasMore: true,
		page: 1,
		pageSize: 20,
		activeFilter: 'lastYear', // lastYear, custom
		startDate: '',
		endDate: '',
		showDatePicker: false,
		cardBalance: '0.00', // 卡内余额
		currentPatient: {
			name: '',
			tag: '本人',
			idNumber: ''
		},
		showPatientModal: false, // 是否显示就诊人选择模态框
		patientList: [] // 就诊人列表
	},

	onLoad() {
		this.loadPatientInfo()
		this.loadCardBalance()
		this.loadRechargeData()
	},

	// 加载患者信息
	loadPatientInfo() {
		console.log('开始加载就诊人信息...')
		console.log('请求URL: http://localhost:8005/patient/list')
		
		// 从后端获取默认就诊人信息
		wx.request({
			url: 'http://localhost:8005/patient/list',
			method: 'GET',
			header: { 'Content-Type': 'application/json' },
			success: (res) => {
				console.log('就诊人信息请求成功:', res)
				console.log('状态码:', res.statusCode)
				console.log('响应数据:', res.data)
				
				if (res.statusCode === 200 && res.data) {
					let list = res.data
					console.log('原始数据:', list)
					
					if (typeof list === 'string') {
						try { 
							list = JSON.parse(list) 
							console.log('解析后的数据:', list)
						} catch (e) { 
							console.error('JSON解析失败:', e)
							return 
						}
					}
					
					if (list.code !== undefined) {
						console.log('数据包含code字段，提取data:', list.data)
						list = list.data
					}
					
					if (!Array.isArray(list)) {
						console.error('数据不是数组:', list)
						return
					}
					
					console.log('处理后的就诊人列表:', list)
					
					// 保存完整的就诊人列表 - 直接使用后端返回的字段名
					const mapped = list.map(p => {
						console.log('处理就诊人:', p)
						return {
							id: p.id,
							name: p.name,
							relation: p.relationTypeName || '本人',
							idNumber: (p.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
							isDefault: p.isDefault === 1
						}
					})
					
					console.log('映射后的就诊人列表:', mapped)
					this.setData({ patientList: mapped })
					
					// 找到默认就诊人
					const defaultPatient = list.find(p => p.isDefault === 1)
					if (defaultPatient) {
						console.log('找到默认就诊人:', defaultPatient)
						this.setData({
							currentPatient: {
								name: defaultPatient.name,
								tag: defaultPatient.relationTypeName || '本人',
								idNumber: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
							}
						})
					} else {
						// 如果没有默认就诊人，使用第一个就诊人
						const firstPatient = list[0]
						if (firstPatient) {
							console.log('使用第一个就诊人:', firstPatient)
							this.setData({
								currentPatient: {
									name: firstPatient.name,
									tag: firstPatient.relationTypeName || '本人',
									idNumber: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
								}
							})
						}
					}
				} else {
					console.error('请求失败或数据为空:', res)
				}
			},
			fail: (err) => {
				console.error('就诊人信息请求失败:', err)
				console.error('错误详情:', err)
			}
		})
	},

	// 加载卡余额
	loadCardBalance() {
		// 获取当前患者ID
		const userInfo = wx.getStorageSync('userInfo')
		const patientId = userInfo ? userInfo.patientId : null
		
		const params = {}
		if (patientId) {
			params.patientId = patientId
			params.patient_id = patientId // 兼容不同后端命名
		}
		
		wx.request({
			url: 'http://localhost:8084/recharge/balance',
			method: 'GET',
			data: params,
			header: {
				'Content-Type': 'application/json',
				'Authorization': wx.getStorageSync('token') || ''
			},
			success: (res) => {
				if (res.statusCode === 200 && res.data) {
					let balanceData = res.data
					
					// 处理数据格式
					if (typeof balanceData === 'string') {
						try {
							balanceData = JSON.parse(balanceData)
						} catch (e) {
							console.error('余额数据解析失败:', e)
							return
						}
					}
					
					// 检查是否为Result格式的响应
					if (balanceData.code !== undefined) {
						if (balanceData.code !== 200) {
							console.error('获取余额失败:', balanceData.message)
							return
						}
						balanceData = balanceData.data
					}
					
					// 更新余额
					const balance = balanceData.balance || balanceData.amount || 0
					this.setData({
						cardBalance: balance.toFixed(2)
					})
					
					console.log('余额更新成功:', balance.toFixed(2))
				}
			},
			fail: (error) => {
				console.error('获取余额失败:', error)
				// 如果获取失败，使用默认余额
				this.setData({
					cardBalance: '0.00'
				})
			}
		})
	},

	onPullDownRefresh() {
		this.setData({
			page: 1,
			hasMore: true,
			rechargeList: []
		})
		this.loadRechargeData()
		wx.stopPullDownRefresh()
	},

	onReachBottom() {
		if (this.data.hasMore && !this.data.loading) {
			this.setData({
				page: this.data.page + 1
			})
			this.loadRechargeData()
		}
	},

	// 加载充值记录数据
	loadRechargeData() {
		if (this.data.loading) return

		this.setData({
			loading: true
		})

		wx.showLoading({
			title: '加载中...'
		})

		// 构建请求参数
		const params = {
			page: this.data.page,
			pageSize: this.data.pageSize,
			bizType: '门诊充值' // 筛选门诊充值记录
		}
		
		// 添加患者ID（如果有）
		const userInfo = wx.getStorageSync('userInfo')
		if (userInfo && userInfo.patientId) {
			params.patientId = userInfo.patientId
			params.patient_id = userInfo.patientId // 兼容不同后端命名
		}

		// 添加日期筛选
		if (this.data.startDate) {
			params.startDate = this.data.startDate
		}
		if (this.data.endDate) {
			params.endDate = this.data.endDate
		}

		wx.request({
			url: 'http://localhost:8084/recharge/list',
			method: 'GET',
			data: params,
			header: {
				'Content-Type': 'application/json',
				'Authorization': wx.getStorageSync('token') || ''
			},
			success: (res) => {
				wx.hideLoading()
				this.setData({
					loading: false
				})

				if (res.statusCode === 200 && res.data) {
					let rechargeData = res.data

					// 处理数据格式
					if (typeof rechargeData === 'string') {
						try {
							rechargeData = JSON.parse(rechargeData)
						} catch (e) {
							console.error('JSON解析失败:', e)
							this.showError('数据格式错误')
							return
						}
					}

					// 检查是否为Result格式的响应
					if (rechargeData.code !== undefined) {
						if (rechargeData.code !== 200) {
							console.error('后端返回错误:', rechargeData.message)
							this.showError(rechargeData.message || '请求失败')
							return
						}
						// 从Result.data中提取实际数据
						rechargeData = rechargeData.data
					}

					// 提取数据数组
					let dataList = []
					if (Array.isArray(rechargeData)) {
						dataList = rechargeData
					} else if (rechargeData && rechargeData.records && Array.isArray(rechargeData.records)) {
						// 处理MyBatis-Plus分页数据
						dataList = rechargeData.records
					} else if (rechargeData && rechargeData.data && Array.isArray(rechargeData.data)) {
						dataList = rechargeData.data
					} else if (rechargeData && rechargeData.list && Array.isArray(rechargeData.list)) {
						dataList = rechargeData.list
					} else if (rechargeData && rechargeData.content && Array.isArray(rechargeData.content)) {
						// 处理其他分页数据
						dataList = rechargeData.content
					} else {
						console.error('数据格式不正确:', rechargeData)
						this.showError('数据格式不正确')
						return
					}

					// 计算每条记录后的余额
					const processedData = this.calculateBalances(dataList)

					// 更新数据
					const newList = this.data.page === 1 ? processedData : [...this.data.rechargeList, ...processedData]
					
					// 检查是否还有更多数据
					let hasMore = processedData.length === this.data.pageSize
					if (rechargeData && rechargeData.total !== undefined) {
						// 使用后端返回的分页信息
						const total = rechargeData.total || 0
						const current = rechargeData.current || 1
						const size = rechargeData.size || this.data.pageSize
						hasMore = (current * size) < total
					}
					
					this.setData({
						rechargeList: newList,
						hasMore: hasMore
					})

					if (this.data.page === 1) {
						wx.showToast({
							title: '数据加载成功',
							icon: 'success'
						})
					}
				} else {
					console.error('加载充值记录失败:', res.statusCode, res.data)
					this.showError(`请求失败: ${res.statusCode}`)
				}
			},
			fail: (error) => {
				wx.hideLoading()
				this.setData({
					loading: false
				})
				console.error('网络请求失败:', error)
				this.showError('网络请求失败')
			}
		})
	},

	// 计算每条记录后的余额
	calculateBalances(dataList) {
		// 按时间排序（从新到旧）
		const sortedData = [...dataList].sort((a, b) => {
			const timeA = new Date(a.operateTime || a.createTime || a.time || 0)
			const timeB = new Date(b.operateTime || b.createTime || b.time || 0)
			return timeB - timeA
		})
		
		// 从当前余额开始，按时间倒序计算每条记录后的余额
		let runningBalance = parseFloat(this.data.cardBalance) || 0
		const balanceMap = new Map()
		
		// 为每条记录计算余额
		sortedData.forEach(item => {
			const itemId = item.orderId || item.id
			const amount = parseFloat(item.amount) || 0
			
			// 如果后端提供了该记录的余额，使用后端数据
			if (item.balance !== undefined && item.balance !== null) {
				balanceMap.set(itemId, parseFloat(item.balance).toFixed(2))
				runningBalance = parseFloat(item.balance)
			} else {
				// 否则从当前余额减去充值金额
				runningBalance = Math.max(0, runningBalance - amount)
				balanceMap.set(itemId, runningBalance.toFixed(2))
			}
		})
		
		// 处理数据并添加计算出的余额
		return dataList.map(item => {
			const itemId = item.orderId || item.id
			const calculatedBalance = balanceMap.get(itemId) || '0.00'
			
			return {
				id: itemId || Math.random().toString(36).substr(2, 9),
				type: item.bizType || item.type || '门诊充值',
				time: this.formatTime(item.operateTime || item.createTime || item.time),
				amount: item.amount > 0 ? `+${item.amount.toFixed(2)}` : `${item.amount.toFixed(2)}`,
				amountClass: item.amount > 0 ? 'positive' : 'negative',
				balance: calculatedBalance,
				orderNumber: item.orderNumber || item.orderNo || '',
				paymentMethod: item.payMethod || item.paymentMethod || '微信支付',
				status: item.payStatus === 1 ? 'success' : (item.payStatus === 2 ? 'pending' : 'failed'),
				source: item.source || '微信小程序'
			}
		})
	},

	// 格式化时间
	formatTime(timeStr) {
		if (!timeStr) return ''
		const date = new Date(timeStr)
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		const hours = String(date.getHours()).padStart(2, '0')
		const minutes = String(date.getMinutes()).padStart(2, '0')
		return `${year}-${month}-${day} ${hours}:${minutes}`
	},

	// 显示错误信息
	showError(message) {
		wx.showToast({
			title: message,
			icon: 'none',
			duration: 2000
		})
	},

	// 筛选按钮点击事件
	onFilterTap(e) {
		const filter = e.currentTarget.dataset.filter
		this.setData({
			activeFilter: filter,
			page: 1,
			hasMore: true,
			rechargeList: []
		})

		switch (filter) {
			case 'today':
				this.loadTodayData()
				break
			case 'week':
				this.loadWeekData()
				break
			case 'month':
				this.loadMonthData()
				break
			case 'custom':
				this.showDatePicker()
				break
			default:
				this.loadRechargeData()
		}
	},

	// 加载今天的数据
	loadTodayData() {
		const today = new Date()
		const startDate = today.toISOString().split('T')[0]
		const endDate = startDate
		
		this.setData({
			startDate: startDate,
			endDate: endDate
		})
		this.loadRechargeData()
	},

	// 加载本周的数据
	loadWeekData() {
		const today = new Date()
		const startOfWeek = new Date(today)
		startOfWeek.setDate(today.getDate() - today.getDay())
		const endOfWeek = new Date(today)
		endOfWeek.setDate(today.getDate() + (6 - today.getDay()))
		
		this.setData({
			startDate: startOfWeek.toISOString().split('T')[0],
			endDate: endOfWeek.toISOString().split('T')[0]
		})
		this.loadRechargeData()
	},

	// 加载本月的数据
	loadMonthData() {
		const today = new Date()
		const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
		const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0)
		
		this.setData({
			startDate: startOfMonth.toISOString().split('T')[0],
			endDate: endOfMonth.toISOString().split('T')[0]
		})
		this.loadRechargeData()
	},

	// 显示日期选择器
	showDatePicker() {
		this.setData({
			showDatePicker: true
		})
	},

	// 日期选择器确认事件
	onDateConfirm(e) {
		const { startDate, endDate } = e.detail
		this.setData({
			startDate: startDate,
			endDate: endDate,
			showDatePicker: false,
			page: 1,
			hasMore: true,
			rechargeList: []
		})
		this.loadRechargeData()
	},

	// 日期选择器取消事件
	onDateCancel() {
		this.setData({
			showDatePicker: false
		})
	},

	// 刷新数据
	refreshData() {
		this.setData({
			page: 1,
			hasMore: true,
			rechargeList: []
		})
		this.loadRechargeData()
	},

	// 查看详情
	viewDetail(e) {
		const item = e.currentTarget.dataset.item
		console.log('查看充值详情:', item)
		
		if (!item || !item.id) {
			wx.showToast({
				title: '数据错误',
				icon: 'none'
			})
			return
		}
		
		// 显示加载提示
		wx.showLoading({
			title: '加载中...'
		})
		
		// 将数据编码后传递给详情页面
		const itemData = encodeURIComponent(JSON.stringify(item))
		wx.navigateTo({
			url: `/pages/2411Ayiliao-pages/recharge/detail?data=${itemData}&id=${item.id}`,
			success: () => {
				wx.hideLoading()
			},
			fail: (error) => {
				wx.hideLoading()
				console.error('页面跳转失败:', error)
				wx.showToast({
					title: '页面跳转失败',
					icon: 'none'
				})
			}
		})
	},

	// 查看详情（备用方法）
	onItemTap(e) {
		const item = e.currentTarget.dataset.item
		wx.navigateTo({
			url: `/pages/2411Ayiliao-pages/recharge/detail?id=${item.id}`
		})
	},

	// 复制订单号
	onCopyOrderNumber(e) {
		const orderNumber = e.currentTarget.dataset.orderNumber
		wx.setClipboardData({
			data: orderNumber,
			success: () => {
				wx.showToast({
					title: '订单号已复制',
					icon: 'success'
				})
			}
		})
	},

	// 切换患者
	switchPatient() {
		// 先加载患者列表
		this.loadPatientList()
	},
	
	// 加载患者列表
	loadPatientList() {
		wx.showLoading({ title: '加载中...' })
		wx.request({
			url: 'http://localhost:8005/patient/list',
			method: 'GET',
			header: { 'Content-Type': 'application/json' },
			success: (res) => {
				wx.hideLoading()
				if (res.statusCode === 200 && res.data) {
					let patientData = res.data
					
					// 处理数据格式
					if (typeof patientData === 'string') {
						try {
							patientData = JSON.parse(patientData)
						} catch (e) {
							console.error('JSON解析失败:', e)
							return
						}
					}
					
					// 处理Result包装的数据
					if (patientData.code !== undefined) {
						if (patientData.code !== 200) {
							console.error('后端返回错误:', patientData.message)
							wx.showToast({
								title: patientData.message || '请求失败',
								icon: 'none'
							})
							return
						}
						patientData = patientData.data
					}
					
					// 提取患者数组
					if (!Array.isArray(patientData)) {
						if (patientData.data && Array.isArray(patientData.data)) {
							patientData = patientData.data
						} else if (patientData.list && Array.isArray(patientData.list)) {
							patientData = patientData.list
						} else if (patientData.patients && Array.isArray(patientData.patients)) {
							patientData = patientData.patients
						} else {
							console.error('数据不是数组格式:', patientData)
							return
						}
					}
					
					// 构建选择列表
					const itemList = patientData.map(patient => 
						`${patient.name || patient.patientName} (${patient.relationTypeName || patient.relationship || '本人'})`
					)
					
					wx.showActionSheet({
						itemList: itemList,
						success: (res) => {
							if (res.tapIndex >= 0 && res.tapIndex < patientData.length) {
								const selectedPatient = patientData[res.tapIndex]
								const selectedPatientId = selectedPatient.id || selectedPatient.patientId
								const patientInfo = {
									name: selectedPatient.name || selectedPatient.patientName,
									tag: selectedPatient.relationTypeName || selectedPatient.relationship || '本人',
									idNumber: selectedPatient.idCardNumber || selectedPatient.idCard || '622*********0909',
									patientId: selectedPatientId
								}
								
								this.setData({
									currentPatient: patientInfo
								})
								
								// 写入本地缓存，供后续接口透传
								const cacheUser = wx.getStorageSync('userInfo') || {}
								wx.setStorageSync('userInfo', { ...cacheUser, patientId: selectedPatientId })
								
								// 重新加载余额和充值记录
								this.loadCardBalance()
								this.setData({
									page: 1,
									hasMore: true,
									rechargeList: []
								})
								this.loadRechargeData()
								
								wx.showToast({
									title: '已切换到' + patientInfo.name,
									icon: 'success'
								})
							}
						}
					})
				} else {
					wx.showToast({
						title: '加载患者列表失败',
						icon: 'none'
					})
				}
			},
			fail: (error) => {
				wx.hideLoading()
				console.error('网络请求失败:', error)
				wx.showToast({
					title: '网络请求失败',
					icon: 'none'
				})
			}
		})
	},

	// 选择筛选条件
	selectFilter(e) {
		const filter = e.currentTarget.dataset.filter
		this.setData({
			activeFilter: filter,
			page: 1,
			hasMore: true,
			rechargeList: []
		})

		if (filter === 'lastYear') {
			// 加载近一年的数据
			const oneYearAgo = new Date()
			oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1)
			
			this.setData({
				startDate: oneYearAgo.toISOString().split('T')[0],
				endDate: new Date().toISOString().split('T')[0]
			})
		}
		
		this.loadRechargeData()
	},

	// 打开日期选择器
	openDatePicker(e) {
		const type = e.currentTarget.dataset.type
		wx.showDatePickerView({
			success: (res) => {
				if (type === 'start') {
					this.setData({ startDate: res.date })
				} else {
					this.setData({ endDate: res.date })
				}
			}
		})
	},

	// 应用日期筛选
	applyDateFilter() {
		if (!this.data.startDate || !this.data.endDate) {
			wx.showToast({
				title: '请选择开始和结束日期',
				icon: 'none'
			})
			return
		}
		
		this.setData({
			page: 1,
			hasMore: true,
			rechargeList: []
		})
		this.loadRechargeData()
	},

	// 重置日期筛选
	resetDateFilter() {
		this.setData({
			startDate: '',
			endDate: '',
			activeFilter: 'lastYear'
		})
		this.selectFilter({ currentTarget: { dataset: { filter: 'lastYear' } } })
	},

	// 测试API端点（长按触发）
	testApiEndpoints() {
		console.log('=== 测试API端点 ===')
		console.log('当前患者信息:', this.data.currentPatient)
		console.log('当前余额:', this.data.cardBalance)
		console.log('充值记录数量:', this.data.rechargeList.length)
		
		wx.showToast({
			title: 'API测试信息已输出到控制台',
			icon: 'none',
			duration: 2000
		})
	},

	// 切换就诊人
	switchPatient() {
		this.setData({ showPatientModal: true })
	},

	// 关闭就诊人选择弹窗
	closePatientModal() {
		this.setData({ showPatientModal: false })
	},

	// 选择就诊人
	selectPatient(e) {
		const patient = e.currentTarget.dataset.patient
		
		// 更新当前就诊人信息
		this.setData({
			currentPatient: {
				name: patient.name,
				tag: patient.relation,
				idNumber: patient.idNumber
			},
			showPatientModal: false
		})
		
		// 保存到本地存储
		const cacheUser = wx.getStorageSync('userInfo') || {}
		wx.setStorageSync('userInfo', { ...cacheUser, patientId: patient.id })
		
		// 重新加载余额和充值记录
		this.loadCardBalance()
		this.loadRechargeData()
		
		wx.showToast({
			title: `已切换到${patient.name}`,
			icon: 'success'
		})
	},

	// 阻止事件冒泡
	stopPropagation() {
		// 空函数，用于阻止事件冒泡
	},

}) 